import React, { useCallback, useEffect, useState } from 'react';
import { Button, Modal, Space, Table, Tag } from 'antd';
import type { TableProps } from 'antd';
import http from '../../api/http';
import type { FormProps } from 'antd';
import { Form, Input } from 'antd';
import type { PopconfirmProps } from 'antd';
import { message, Popconfirm } from 'antd';

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}

const App: React.FC = () => {

  // 定义表格数据
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [title, setTitle] = useState('');
  const [tag, setTag] = useState('');
  const [forms] = Form.useForm();
  const [form] = Form.useForm();

  // 获取表格数据
  const fetchList = async () => {
    const params: {
      page: number,
      pageSize: number,
      keyword?: string,
      tag?: string
    } = {
      page,
      pageSize
    }
    if (title) params.keyword = title;
    if (tag) params.tag = tag;
    const res = await http.get('/article/list', {
      params
    })
    console.log(res, '表格数据');
    const { count, rows } = res.data;
    setList(rows);
    setTotal(count)
  }
  // 回调
  useEffect(() => {
    fetchList()
  }, [page, pageSize, title, tag])

  // 分页
  const change = (page: number, pageSize: number) => {
    setPage(page)
    setPageSize(pageSize)
  }
  // 搜索
  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    setTitle(values.title);
    setTag(values.tag);
  };
  // 重置
  const handleReact = () => {
    setTitle('');
    setTag('');
    forms.resetFields()
  }
  // 删除
  const confirm: PopconfirmProps['onConfirm'] = useCallback((id) => {
    const newData = list.filter((item) => item.id !== id)
    setList(newData)
  }, [list])

  const cancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e);
    message.error('Click on No');
  };

  // 弹框
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [flag,setFlag] = useState(false)

  // 编辑
  const handleEdit = (row) =>{
    setFlag(true);
    setOpen(true);
    form.setFieldsValue(row)
  }

  // 新增-编辑
  const handleOk = async () => {
    setFlag(true)
    const {id,content,title} = form.getFieldsValue()
    if(!flag){
      const res = await http.post('/article', {
      title,
      content,
      tagList: ["前端"],
      categoryList: ["IT"],
      authorId: '47529555'
    })
    console.log(res,'新增信息');
    setOpen(false);
    setConfirmLoading(false);
    fetchList();
    form.resetFields()
    }else{
      const res = await http.put(`/article/${id}`, {
      title,
      content,
      tagList: ["前端编辑"],
      categoryList: ["IT1"],
      authorId: '47529555'
    })
    console.log(res,'编辑信息');
    setOpen(false);
    setConfirmLoading(false);
    fetchList();
    form.resetFields()
    }
  };

  const handleCancel = () => {
    console.log('取消');
    setOpen(false);
  };


  // 渲染
  const columns: TableProps<DataType>['columns'] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '浏览量',
      dataIndex: 'viewCount',
      key: 'viewCount',
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
    },
    {
      title: '标签',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.name.length > 5 ? 'geekblue' : 'green';
            return (
              <Tag color={color} key={tag.name}>
                {tag.name.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '分类',
      key: 'categories',
      dataIndex: 'categories',
      render: (_, { categories }) => (
        <>
          {categories.map((tag) => {
            let color = tag.name.length > 5 ? 'geekblue' : 'green';
            return (
              <Tag color={color} key={tag.name}>
                {tag.name.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button color="default" variant="filled">
            查看
          </Button>
          <Button onClick={()=>handleEdit(record)} color="primary" variant="filled">
            编辑
          </Button>
          <Popconfirm
            title='删除列表'
            description="您真的要删除吗?"
            onConfirm={() => confirm(record.id)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button color="danger" variant="filled">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];



  return (
    <div>
      {/* 搜索表单 */}
      <Form
        name="basic"
        layout='inline'
        form={forms}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 1600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="标题"
          name="title"
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="标签"
          name="tag"
        >
          <Input />
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" onClick={() => handleReact()}>
            重置
          </Button>
        </Form.Item>
      </Form>
      <br />
      <hr />
      <Button onClick={() => setOpen(true)} color="purple" variant="outlined">
        新增数据 +
      </Button>
      <br />
      {/* 表格 */}
      <Table<DataType>
        columns={columns}
        dataSource={list}
        pagination={{
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `Total ${total} items`,
          onChange: change
        }}
      />
      {/* 新增/编辑 */}
      <Modal
        title="Title"
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >

          <Form.Item<FieldType>
            label="ID"
            name="id"
          >
            <Input disabled />
          </Form.Item>

          <Form.Item<FieldType>
            label="标题"
            name="title"
          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType>
            label="内容"
            name="content"
          >
            <Input />
          </Form.Item>

        </Form>
      </Modal>
    </div>
  )
}

export default App;